home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_04 / allison / recurse.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-02-10  |  809 b   |  52 lines

  1. LISTING 4 -
  2. /* recurse.c:  Illustrate recursion and storage duration */
  3.  
  4. #include <stdio.h>
  5.  
  6. main()
  7. {
  8.     long n;
  9.     long fac(long);
  10.  
  11.     fputs("Enter a small integer: ",stderr);
  12.     scanf("%ld%*c",&n);
  13.     printf("\n%ld! = %ld\n",n,fac(n));
  14.     return 0;
  15. }
  16.  
  17. long fac(long n)
  18. {
  19.     static int depth = 0;
  20.     auto long result;
  21.     void print_current(int,long);
  22.  
  23.     print_current(++depth,n);
  24.     result = (n <= 1) ? 1 : n * fac(n-1);
  25.     print_current(depth--,result);
  26.  
  27.     return result;
  28. }
  29.  
  30. void print_current(int depth, long n)
  31. {
  32.     int i;
  33.  
  34.     /* Indent to show depth */
  35.     for (i = 0; i < depth; ++i)
  36.         fputs("   ",stdout);
  37.  
  38.     printf("%ld\n",n);
  39. }
  40.  
  41. /* Output:
  42. Enter a small integer: 3
  43.    3
  44.       2
  45.          1
  46.          1
  47.       2
  48.    6
  49.  
  50. 3! = 6
  51. */
  52.